package com.open.capacity.user.service.impl;

import com.open.capacity.commons.CodeEnum;
import com.open.capacity.commons.PageResult;
import com.open.capacity.commons.Result;
import com.open.capacity.model.system.constants.UserType;
import com.open.capacity.reimburse.util.uuid.UUIDUtils;
import com.open.capacity.user.dao.SysEmployeeDao;
import com.open.capacity.user.model.SysEmployee;
import com.open.capacity.user.service.SysEmployeeService;
import com.open.capacity.user.vo.SysUserVo;
import com.open.capacity.utils.PageUtil;
import com.open.capacity.utils.ValidatorUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import java.util.*;

/**
 * @author 作者 ftquan E-mail: 464725602@qq.com
 * @version 创建时间：2017年11月12日 上午22:57:51
 */
@Slf4j
@Service
public class SysEmployeeServiceImpl implements SysEmployeeService {

    @Autowired
    private SysEmployeeDao userDao;


    @Transactional(rollbackFor = Exception.class)
    @Override
    public SysEmployee updateEmployee(SysEmployee employee) {
        employee.setUpdateTime(new Date());
        userDao.updateByOps(employee);
        log.info("修改員工：{}", employee);
        return employee;
    }



    @Transactional(rollbackFor = Exception.class)
    @Override
    public SysEmployee findByUsername(String username) {
        SysEmployee employee = userDao.findByUsername(username);
        return employee;
    }

    @Override
    public SysEmployee findById(String id) {
        SysEmployee user = userDao.findById(id);
        return user;
    }



    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result updateStatus(String id, Integer status) {
        SysEmployee employee = new SysEmployee();
        employee.setId(id);
        employee.setStatus(status);
        updateEmployee(employee);
        log.info("修改状态：{}", employee);
        return Result.succeed("修改成功");
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public int delete(String id) {
        userDao.delete(id);
        return 1;
    }

    @Override
    public List<SysEmployee> findAll(Map<String, Object> params) {
        return userDao.findList(params);
    }


    @Override
    public PageResult<SysEmployee> pageAll(Map<String, Object> params) {
        int total = userDao.count(params);
        List<SysEmployee> list = Collections.emptyList();
        if (total > 0) {
            PageUtil.pageParamConver(params, true);
            list = userDao.findList(params);
        }
        return PageResult.<SysEmployee>builder().data(list).resp_code(CodeEnum.SUCCESS.getCode()).count((long) total).build();
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public Result saveOrUpdate(SysEmployee employee, String keyValue) {
        String username = employee.getUserName();
        if (StringUtils.isBlank(username)) {
            //throw new IllegalArgumentException("用户名不能为空");
            return Result.failed("用户名不能为空");
        }

        if (ValidatorUtil.checkPhone(username)) {// 防止用手机号直接当用户名，手机号要发短信验证
            //throw new IllegalArgumentException("用户名要包含英文字符");
            return Result.failed("用户名要包含英文字符");
        }

        if (username.contains("@")) {// 防止用邮箱直接当用户名，邮箱也要发送验证（暂未开发）
            //throw new IllegalArgumentException("用户名不能包含@");
            return Result.failed("用户名不能包含@");
        }

        if (username.contains("|")) {
            //throw new IllegalArgumentException("用户名不能包含|字符");
            return Result.failed("用户名不能包含|字符");
        }

        if (StringUtils.isBlank(employee.getNickName())) {
            employee.setNickName(username);
        }

        if (StringUtils.isBlank(employee.getType())) {
            employee.setType(UserType.BACKEND.name());
        }

        if (!StringUtils.isBlank(employee.getPhone())) {
            if (!ValidatorUtil.checkPhone(employee.getPhone())) {// 防止用手机号直接当用户名，手机号要发短信验证
                //throw new IllegalArgumentException("用户名要包含英文字符");
                return Result.failed("手机号格式不正确");
            }
        }


        employee.setStatus(1);
        employee.setCreateTime(new Date());

        int i;
        if (StringUtils.isEmpty(keyValue)) {
            SysEmployee persistenceUser = userDao.findByUsername(employee.getUserName());
            if (persistenceUser != null && persistenceUser.getUserName() != null) {
                //throw new IllegalArgumentException("用户名已存在");
                return Result.failed("用户名已存在");
            }

            employee.setId(UUIDUtils.getOriginalUUIDWithoutBar());
            employee.setUpdateTime(employee.getCreateTime());
            i = userDao.save(employee);
        } else {
            employee.setId(keyValue);
            employee.setUpdateTime(new Date());

            i = userDao.updateByOps(employee);
        }

        return i > 0 ? Result.succeed(employee, "操作成功") : Result.failed("操作失败");
    }


    @Override
    public Map<String, SysUserVo> getMap() {
        Map<String, SysUserVo> map = new HashMap<>();
        Map<String, Object> params = new HashMap<>();
        List<SysEmployee> list = userDao.findList(params);
        SysUserVo vo;
        for (SysEmployee item : list) {
            vo = new SysUserVo();
            vo.setCompanyId(item.getCompanyId());
            vo.setDepartmentId(item.getDepartmentId());
            vo.setName(item.getRealName());
            map.put(item.getId(), vo);
        }
        return map;
    }


    @Transactional(rollbackFor = Exception.class)
    @Override
    public int importExcel(MultipartFile multipartFile, String companyId) throws Exception {
        return 1;
//        ImportParams params = new ImportParams();
//        params.setHeadRows(1);
//        // params.setTitleRows(0);
//        // 开启excel校验
//        params.setNeedVerify(true);
//
//        ExcelImportResult<KjkmExcelModel> result = new ExcelImportResult();
//        try {
//            result = ExcelImportUtil.importExcelMore(multipartFile.getInputStream(),
//                    KjkmExcelModel.class, params);
//        } catch (Exception e) {
//
//            log.error("从文件读取数据错误:{}", e.getMessage());
//        }
//        if (result.isVerifyFail()) {
//            StringBuilder temp = new StringBuilder();
//            for (KjkmExcelModel entity : result.getFailList()) {
//                temp.append("第").append(entity.getRowNum()).append("行的错误是：").append(entity.getErrorMsg());
//            }
//            throw new Exception("Excel文件校验不通过:" + temp.toString());
//        }
//
//
//        return result.getList().size();
    }
}
